package thingapi

import (
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	"iot-base/common/webapi"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/tidwall/gjson"
)

func getQueryProperty(c *gin.Context) bool {
	query := c.Param("id")
	if query == "query" {
		isPublished := c.Query("published")
		if isPublished == "true" {
			name := c.Query("type")
			if name != "" {
				sql := `select DISTINCT property->>'identifier',property as body
					from t_models tm,jsonb_array_elements(tm.body->?) property
					where property->>'published' = 'true'`
				var result []JSONBody
				err := dbconn.DBConnection.Raw(sql, name).Find(&result).Error
				if err != nil {
					webapi.SendError(err.Error(), webapi.DBError, c)
				} else {
					webapi.SendResult(result, nil, c)
				}
			} else {
				webapi.SendError("name param_missed", webapi.ParamMissed, c)
			}
			//return true

			//Select("body::jsonb->'properties'->>'identifier' as pid,body::jsonb->'properties'->>'name' as name,")
		}

		return true
	}

	return false
}
func SaveTModel(model *dbobj.TModel) *dbobj.TModel {

	if model.Body != nil {
		jbody := gjson.Parse(string(model.Body))
		jproperties := jbody.Get("properties")

		if jproperties.IsArray() {
			for _, p := range jproperties.Array() {
				jtype := p.Get("data_type.type")
				stype := jtype.String()
				if stype == "stream" {
					model.HasStream = true
					return model
				} else {
					var jspecs gjson.Result
					switch stype {
					case "struct", "array":
						jspecs = p.Get("data_type.specs")
						if !jspecs.IsArray() {
							jspecs = p.Get("data_type.specs.item.specs")
						}
					default:
						return model

					}
					if jspecs.IsArray() {
						for _, spec := range jspecs.Array() {
							jtype := spec.Get("data_type.type")
							stype := jtype.String()
							if stype == "stream" {
								model.HasStream = true
								break
							}
						}
					}
				}

			}
		}

	}

	return model
}

func hasStream(c *gin.Context) *TModelEx {
	var model TModelEx
	if err := c.ShouldBindBodyWith(&model, binding.JSON); err != nil {
		webapi.SendError("tmodel "+err.Error(), webapi.ParamMissed, c)
		return nil
	}

	SaveTModel(&model.TModel)
	return &model
}

//TModelEx 客户端发送的tmodel信息
type TModelEx struct {
	dbobj.TModel
	Path []string `json:"path"`
}

func saveModel(c *gin.Context) bool {
	model := hasStream(c)
	if model == nil {
		return false
	}
	if len(model.Path) > 0 {
		parent := ""
		for _, path := range model.Path {
			var catalog dbobj.Catalog
			catalog.UID = path
			catalog.ParentID = parent
			err := dbconn.DBConnection.First(&catalog).Error
			if err != nil {
				catalog.SName = path
				dbconn.DBConnection.Save(&catalog)
			}
			parent = path
		}
	}
	method := c.Request.Method
	var errdb error
	if method == "POST" {
		errdb = dbconn.NewItem(&model.TModel)
	} else {
		errdb = dbconn.Update(&model.TModel)
	}
	if errdb != nil {
		webapi.SendError(errdb.Error(), webapi.DBError, c)
		//return true
	} else {
		webapi.SendResult(model, nil, c)
	}
	return true
}
